package com.example.demo.service.impl;


import com.example.demo.dao.CustomerDao;
import com.example.demo.entity.response.Response;
import com.example.demo.entity.sqlbean.Customer;
import com.example.demo.service.CustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class CustomerServiceImpl implements CustomerService {

    @Resource
    CustomerDao customerDao;

    /**
     * token
     */
    @Override
    public Customer findCustomer(String machineCode) { return customerDao.selectCustomer(machineCode); }

    @Override
    public Response loginCustomer(Customer customer) {

        final List<String> is_ok =customerDao.selectAll();

        Response response ;
        Customer customers = customerDao.selectCustomerAccountPwd(customer.getAccount(), customer.getPassword());
        if (customers == null) {
            response = Response.error(1001,"账号密码错误");
            return  response;
        }
        String machineCode = customer.getMachineCode();
        if ( !(is_ok.contains(machineCode))  && Objects.equals(customers.getMachineCode(), "") ){
            int result = customerDao.updateCustomerMachineCode(customer.getAccount(), customer.getPassword(),machineCode);
            if (result !=1){
                response = Response.error(1003,"登录失败");
            }
            else{
                customers = customerDao.selectCustomerAccountPwd(customer.getAccount(), customer.getPassword());
                response = Response.success(customers);
                log.info(String.valueOf(response));
            }
            return response;
        }
        else if (!(customers.getMachineCode().equals(machineCode)) )
        {
            response = Response.error(1002,"非法设备");
        }
        else{
            customers = customerDao.selectCustomerAccountPwd(customer.getAccount(), customer.getPassword());
            response = Response.success(customers);
            return response;
        }

        return response;
    }

    @Override
    public Response binding(String machineCode) {
        Response response;
        Customer customer = customerDao.selectCustomer(machineCode);
        if (customer == null){
            response = Response.success(100);
            return response;
        }
        response = Response.success(200);
        return response;
    }


}
